import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:math' as math;
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:flutter_application_testview/model/heartRate_data.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';

class ForegroundService {

  // 删除原 requestPermissions() 方法
  // 修改 checkPermissions() 为统一的权限处理入口
  Future<bool> checkPermissions(BuildContext context) async {
    // ▼ 添加互斥锁防止重复请求
    if (_isRequestingPermissions) return false;
    _isRequestingPermissions = true;

    try {
      final permissionsToRequest = [
        Permission.bluetooth,
        Permission.bluetoothScan,
        Permission.bluetoothConnect,
        Permission.location,
        if (Platform.isAndroid) ...[
          Permission.notification,
        ]
      ];

      final statuses = await permissionsToRequest.request();

      // ▼ 合并处理 Android 13+ 的权限跳转逻辑
      if (Platform.isAndroid) {
        //final androidInfo = await DeviceInfoPlugin().androidInfo();
        final androidInfo = await DeviceInfoPlugin().androidInfo;
        if (androidInfo.version.sdkInt >= 33 &&
            !await FlutterForegroundTask.isIgnoringBatteryOptimizations) {
          await FlutterForegroundTask.requestIgnoreBatteryOptimization();
        }
      }

      // ▼ 统一处理拒绝权限提示
      final denied = statuses.entries.where((e) => !e.value.isGranted);
      // if (denied.isNotEmpty) {
      //   await showDialog(context, denied.map((e) => e.key));
      //   return false;
      // }
          if (denied.isNotEmpty) {
      // 显示权限拒绝提示
      await showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('权限请求被拒绝'),
            content: Text('以下权限被拒绝：\n${denied.map((e) => e.key).join('\n')}'),
            actions: <Widget>[
              TextButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
      return false;
    }
      return true;
    } finally {
      _isRequestingPermissions = false;
    }
  }

  bool _isRequestingPermissions = false; // 互斥锁变量

  /// 初始化服务,并检查权限
  Future<void> initService(BuildContext context) async {
    final hasPermission = await checkPermissions(context);
    if (!hasPermission) return;
   // Add a callback to receive data sent from the TaskHandler.
    FlutterForegroundTask.addTaskDataCallback(_onReceiveTaskData);

      FlutterForegroundTask.init(
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'hr_monitor',
        channelName: '健康监测服务',
        channelDescription:
            '持续监测蓝牙心率数据',
        onlyAlertOnce: true,
        priority:NotificationPriority.MAX,
      ),

      iosNotificationOptions: const IOSNotificationOptions(
        showNotification: true,
        playSound: false,
      ),
      foregroundTaskOptions: ForegroundTaskOptions(
        eventAction: ForegroundTaskEventAction.repeat(3000),
        autoRunOnBoot: true,
        autoRunOnMyPackageReplaced: true,
        allowWakeLock: true,
        allowWifiLock: true,
      
      ),
    
    );
  }
Future<void> startServiceWithCheck() async {
  try {
    // 确保所有准备工作在启动服务前完成
    await _prepareForServiceStart();

    final result = await _startService().timeout(
        const Duration(seconds: 10),
        onTimeout: () => throw ServiceTimeoutException('Service start timed out after 10 seconds')
    );

    if (result is ServiceRequestFailure) {
      print('服务启动失败: ${result.error}');
      //Get.snackbar('错误', '服务启动失败: ${result.error}');
    } else {
      print('服务启动成功');
      startSimulation();
    }
  } on ServiceTimeoutException catch (e) {
    print('服务启动超时: $e');
    //Get.snackbar('错误', '服务启动超时，请检查设备设置');
  } catch (e) {
    print('未知错误: $e');
    // ScaffoldMessenger.of(context).showSnackBar(
    //   SnackBar(content: Text('发生未知错误: $e')),
    // );
  }
}
Future<void> _prepareForServiceStart() async {

  // 检查电池优化设置
  // if (Platform.isAndroid && !await FlutterForegroundTask.isIgnoringBatteryOptimizations) {
  //   await FlutterForegroundTask.requestIgnoreBatteryOptimization();
  // }
}
Future<ServiceRequestResult> _startService() async {
    if (await FlutterForegroundTask.isRunningService) {
      return FlutterForegroundTask.restartService();
    } else {
      return FlutterForegroundTask.startService(
        serviceId: 256,
        notificationTitle: '心率监测中',
        notificationText: '正在接收蓝牙心率数据',
        notificationIcon: const NotificationIcon(
    metaDataName: 'ic_launcher', // 必须与AndroidManifest.xml中的meta-data名称一致
    backgroundColor: Color(0xFF2196F3), // 可选背景色
  ),
        // notificationButtons: [
        //   const NotificationButton(id: 'btn_hello', text: 'hello'),
        // ],
        // notificationInitialRoute: '/second',
        // callback: _startBackgroundTask,
      
      );
    }
  }
 // 新增模拟数据生成器
  final _simulator = HeartRateSimulator();
    // 启动模拟数据生成
  void startSimulation() {
    print('启动模拟数据生成器');

    _simulator.start((int rate) {
      var time = DateFormat('HH:mm:ss').format(DateTime.now());
      FlutterForegroundTask.updateService(
      notificationTitle: '健康监测服务',
      notificationText: '时间：${time} 心率：${rate.toString()}',
);
      // 更新数据存储
      //HeartRateData.instance.addData(rate, DateTime.now());
      print('生成模拟数据：$rate');
      // 发送数据到前台任务
      FlutterForegroundTask.sendDataToTask({
        'type': 'heart_rate',
        'value': rate
      });
    });
  }
  ///接收任务数据时
 void _onReceiveTaskData(Object data) {
    print('onReceiveTaskData: $data');
   
  }
///回调
  @pragma('vm:entry-point')
  static void _startBackgroundTask() {
    FlutterForegroundTask.setTaskHandler(HeartRateTaskHandler());
  }


  Future<ServiceRequestResult> stopService() {
    return FlutterForegroundTask.stopService();
  }

}

class HeartRateTaskHandler extends TaskHandler {
  // @override
  // Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
  //   // 初始化后台BLE处理
  //   IsolateNameServer.registerPortWithName(
  //     starter.sendPort,
  //     'hr_background_port'
  //   );
  // }
    @override
  Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
    print('onStart(starter: ${starter.name})');
   
  }

  @override
  void onRepeatEvent(DateTime timestamp) {
    // 每5秒持久化数据
    HeartRateData.instance.saveToStorage();

  }

   Future<void> onDestroy(DateTime timestamp) async {
    print('销毁事件');
  }
}

// 2. 添加心率模拟器类
class HeartRateSimulator {
  Timer? _timer;
  final _random = math.Random();
  Function(int)? _callback;

  void start(Function(int) callback) {
    _callback = callback;
    _timer = Timer.periodic(Duration(seconds: 1), (_) {
      final base = 60 + _random.nextInt(20);  // 基础心率60-80
      final variation = _random.nextInt(10) - 5; // ±5波动
      final rate = base + variation;
      _callback?.call(rate);
    });
  }

  void stop() {
    _timer?.cancel();
    _callback = null;
  }
}
